package oss

import (
	"fmt"
	"gitee.com/DonHz/cloud-file-storage/config"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var ossCli *oss.Client

// 获取oss客户端
func OsClient() *oss.Client {
	if ossCli != nil {
		return ossCli
	}
	ossCli, err := oss.New(config.OSSEndpoint, config.OSSAccessKeyID, config.OSSAccessKeySecret)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return ossCli
}

// 获取bucket存储空间
func Bucket() *oss.Bucket {
	cli := OsClient()
	if cli == nil {
		return nil
	}
	bucket, err := cli.Bucket(config.OSSBucket)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return bucket
}

// 临时授权下载url
func DownloadURL(objectName string) string {
	signedURL, err := Bucket().SignURL(objectName, oss.HTTPGet, 3600)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	return signedURL
}

// 针对指定的bucket设置生命周期规则
func BuildLifecycleRule(bucketName string) {
	// 表示前缀为test的对象（文件）距最后修改时间30天后过期。
	ruleTest1 := oss.BuildLifecycleRuleByDays("rule1", "test/", true, 30)
	rules := []oss.LifecycleRule{ruleTest1}
	OsClient().SetBucketLifecycle(bucketName, rules)
}
